
package org.yaukie.auth.config;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import org.springframework.security.crypto.password.PasswordEncoder;

public class Md5PasswordEncoder implements PasswordEncoder {
    private static final String[] HEX_DIGITS = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private String salt;
    private static Md5PasswordEncoder instance = new Md5PasswordEncoder();

    public void setSalt(String salt) {
        this.salt = salt;
    }

    private Md5PasswordEncoder() {
    }

    public static Md5PasswordEncoder getInstance() {
        return instance;
    }

    private String mergePasswordAndSalt(CharSequence password) {
        if (password == null) {
            password = "";
        }

        return this.salt != null && !"".equals(this.salt) ? password + "{" + this.salt + "}" : ((CharSequence)password).toString();
    }

    private String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        byte[] var3 = b;
        int var4 = b.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            byte value = var3[var5];
            resultSb.append(this.byteToHexString(value));
        }

        return resultSb.toString();
    }

    private String byteToHexString(byte b) {
        int n = b;
        if (b < 0) {
            n = 256 + b;
        }

        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    public String encode(CharSequence rawPassword) {
        String result = null;

        try {
            String algorithm = "MD5";
            MessageDigest md = MessageDigest.getInstance(algorithm);
            result = this.byteArrayToHexString(md.digest(this.mergePasswordAndSalt(rawPassword).getBytes(StandardCharsets.UTF_8)));
        } catch (Exception var5) {
        }

        return result;
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(this.encode(rawPassword));
    }
}
